<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-divider>基本信息</a-divider>
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
              <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
              <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
              <select-user-by-dep
                placeholder="请选择申请人"
                v-model="model.handlerId"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerDeptId">
              <j-select-depart
                placeholder="请选择申请部门"
                v-model="model.handlerDeptId"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-divider>项目信息</a-divider>
          <a-col :span="8">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <select-project-input
                v-if="!formDisabled"
                v-model="model.projectId"
                placeholder="请输入选择项目"
                :proDisabled="true"
                :projectStatus="'2'"
                :disabled="formDisabled"
                @back="handleProjectIdChange"/>
              <a-input
                v-else
                :readOnly="true"
                v-model="model.projectId_dictText"
                style="color: #1890FF;"
                @click.prevent="getProjectDetail(model.projectId)"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="finalNo">
              <a-input
                :disabled="autoFieldDisabled"
                v-model="model.finalNo"
                :max-length="36"
                placeholder="请输入项目编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractId">
              <!--              <select-contract-manager-input-->
              <!--                :muitFlag = "true"-->
              <!--                :disabled="autoFieldDisabled"-->
              <!--                v-model="model.contractId"-->
              <!--                :allList="true"-->
              <!--                :status = "'2'"-->
              <!--                :showName="1"-->
              <!--                :changeStatus = "'unchanged'"-->
              <!--                @change="htbhChange"-->
              <!--                :triggerChange="true"-->
              <!--                @click.prevent="getContractDetail(model.contractId)"-->
              <!--              />-->
              <a-input
                :readOnly="true"
                v-model="model.contractName"
                style="color: #1890FF;"
                placeholder="请选择合同名称"
                @click.prevent="getContractDetail(model.contractId)"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="undertaker">
              <select-user-by-dep
                :disabled="autoFieldDisabled"
                placeholder="请选择项目承接人"
                v-model="model.undertaker"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamName">
              <select-team-input
                :disabled="autoFieldDisabled"
                v-model="model.teamName"
                placeholder="请选择经营团队"
                :tdlx="1"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productTeamName">
              <a-input
                :title="model.productTeamName"
                placeholder="请选择生产团队"
                :disabled="autoFieldDisabled"
                v-model="model.productTeamName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <a-input
                :disabled="autoFieldDisabled"
                v-model="model.year"
                :max-length="36"
                placeholder="请输入业绩归属年度"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signUnit">
              <select-company-input
                :disabled="autoFieldDisabled"
                v-model="model.signUnit"
                placeholder="请选择签订单位"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ownerUnit">
              <select-customer-input
                :disabled="autoFieldDisabled"
                v-model="model.ownerUnit"
                commercialType="1"
                placeholder="请选择业主单位"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="诉讼说明"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="litigationInstruction">
              <a-textarea
                :disabled="formDisabled"
                :max-length="500"
                v-model="model.litigationInstruction"
                rows="6"
                placeholder="请输入诉讼说明"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="48">
          <a-divider>诉讼信息</a-divider>
          <erp-audit-litigation-dt-list :disabled="formDisabled" ref="detailList"></erp-audit-litigation-dt-list>
          <a-col :span="24">
            <a-form-model-item label="任务附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="file">
              <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.file"></j-upload>
              <a-button v-else icon="download" @click="viewFile(model.file)">文件列表</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
        <common-flow-list
          v-if="formBpm && model.bpmStatus !== '1'"
          :formData="formData"
          style="margin-top: 10px"></common-flow-list>
      </a-form-model>
      <!-- 项目详情 -->
      <erp-project-report-modal ref="reportForm"></erp-project-report-modal>
      <!-- 合同详情 -->
      <erp-project-contract-manager-final-form ref="contractForm"></erp-project-contract-manager-final-form>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>

    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center; margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpAuditLitigationFormPrint v-if="formBpm" class="print_style" id="auditLitigation" :formData="model" :formDataHistory="formData"></ErpAuditLitigationFormPrint>
  </a-spin>
</template>

<script>

import { filterMultiDictText, initDictOptions } from '@comp/dict/JDictSelectUtil';
import { getAction, httpAction } from '@/api/manage'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import { mapGetters } from 'vuex'
import { viewFile } from '@/utils/util';
import ErpAuditLitigationDtList from '../ErpAuditLitigationDtList.vue';
import SelectContractManagerInput from '@/views/scy/components/SelectContractManagerInput'
import moment from 'moment'
import ErpProjectContractManagerFinalForm from '../../../report/project/modules/ErpProjectContractManagerFinalForm.vue';
import Print from '@/utils/print/printarea.js';
  import ErpAuditLitigationFormPrint from './ErpAuditLitigationFormPrint' // 打印
export default {
  name: 'ErpAuditLitigationForm',
  mixins: [viewFile],
  components: {
    ErpProjectContractManagerFinalForm,
    ErpAuditLitigationDtList,
    SelectUserByDep,
    SelectTeamInput,
    SelectCompanyInput,
    SelectCustomerInput,
    SelectProjectInput,
    ErpProjectReportModal,
    ViewFileModal,
    CommonFlowList,
    SelectContractManagerInput,
    ErpAuditLitigationFormPrint
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {},
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        litigationInstruction: [
          { required: true, message: '请输入诉讼说明!' }
        ],
        projectId: [
          { required: true, message: '请选择项目!' }
        ]
      },
      dictOptions: {},
      url: {
        add: '/api/erp/audit/litigation/erpAuditLitigation/add',
        edit: '/api/erp/audit/litigation/erpAuditLitigation/edit',
        queryById: '/api/erp/audit/litigation/erpAuditLitigation/queryById',
        // 穿透项目名称
        queryProjectReportById: '/api/erp/project/report/erpProjectReport/queryById',
        // 获取表单编号
        getBillNo: '/api/erp/audit/litigation/erpAuditLitigation/getBillNo',
        // 合同
        queryContractFinal: '/api/erp/omc/contractmanager/erpOmcContractManagerFinal/listForAudit',
        queryProjectTaskList: '/api/erp/omc/project/erpOmcProjectTask/list',
        // 收款进度
        queryProgressPaymentNode: '/api/erp/progress/erpProgressPaymentNode/queryListByContractId'
      }
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    // 带出不可编辑
    autoFieldDisabled() {
      return true;
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData();
    // 字典
    this.initDictOptions()
  },
  methods: {
    ...mapGetters(['userInfo']),
    initDictOptions() {
      // 费用所属团队
      initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'teamId', res.result)
        }
      })
    },
    // 获取单据编号
    getBillNo() {
      getAction(this.url.getBillNo).then((res) => {
        if (res.success) {
          // that.$set(that,'billNo',res.result)
          this.$set(this.model, 'billNo', res.result)
        }
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.check()
      })
    },
    // 校验自动带出的基本信息都带出来没
    check() {
      if (!this.model.billNo || !this.model.handlerId || !this.model.handlerDeptId || !this.model.createTime) {
        this.$message.error('请刷新缓存后重试!')
      }
    },
    add() {
      this.edit(this.modelDefault);
      // 基本信息
      this.userName = this.userInfo().empName;// 当前登录人名称
      this.model.handlerId = this.userInfo().empId; // 当前登录人
      this.model.handlerDeptId = this.userInfo().deptId; // 当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      this.getBillNo() // 获取单据编号
    },
    edit(record) {
      this.userName = this.userInfo().empName;// 当前登录人名称
      this.$refs.form.resetFields();
      this.model = Object.assign({}, record);
      this.$refs.detailList.queryParam.mainId = this.model.id
      this.$refs.detailList.loadData()
      this.visible = true;
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result);
          }
        });
      }
    },

    submitForm(type) {
      const that = this;
      if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
             // 有没有带出收款合同
            if (!that.model.contractId) {
              that.$message.warning('该项目还未签收款合同!')
              that.confirmLoading = false;
              that.$emit('unButtonDisable');
              return;
            }
            // 子表
            this.model.auditLitigationDetail = this.$refs.detailList.dataSource || []
            // 检查子表的必填项
            let checked = this.checkDetail()
            if (!checked) {
              return;
            }
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
    },
    submit (type) {
      const that = this;
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }

      // 子表
      this.model.auditLitigationDetail = this.$refs.detailList.dataSource || []
      // 标题 表单名称+项目名称+发起人+申请日期
      let date = this.getCreateTime()
      if (this.model.projectId_dictText) {
        this.$set(this.model, 'projectName', this.model.projectId_dictText)
      }
      this.model.bpmBizTitle = '诉讼申请单' + '-' + (this.model.projectName ? this.model.projectName + '-' : '') + this.userName + '-' + date
      httpAction(httpurl, this.model, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          if (method == 'post') {
            that.model.id = res.result;
          }
          that.$emit('ok', type, that.model);
        } else {
          that.$message.warning(res.message);
          that.$emit('unButtonDisable');
        }
      }).catch((error) => {
        that.$emit('unButtonDisable', error);
      }).finally(() => {
        that.confirmLoading = false;
      })
    },
    async handleProjectIdChange(data) {
      // contractId
      await this.resetAutoFields()
      if (data.length === 0) {
        return;
      }
      // productTeam 生产团队
      let project = data[0];
      this.$set(this.model, 'projectName', project.projectName)
      // 查合同
      await getAction(this.url.queryContractFinal, { xmmc: this.model.projectId, htlx: 1 }).then(async (res) => {
        if (res.success && !!res.result && !!res.result.records[0]) {
          this.$set(this.model, 'contractId', res.result.records[0].id || '')
          this.$set(this.model, 'contractName', res.result.records[0].htmc || '')
          await getAction(this.url.queryProgressPaymentNode, { contractId: this.model.contractId }).then(res => {
            if (res.success) {
              if (res.result.length > 0) {
                res.result.forEach(item => {
                  // nodeName paymentMoney
                  let node = { paymentNodeName: item.nodeName, paymentMoney: item.paymentMoney }
                  this.$refs.detailList.dataOne(node, true)
                })
              }
            }
          })
        }
      })
      // 项目编号 finalNo
      this.$set(this.model, 'finalNo', project.finalNo)
      // 项目承接人 undertaker
      this.$set(this.model, 'undertaker', project.undertaker)
      // teamName 经营团队
      this.$set(this.model, 'teamName', project.teamName)
      // 查出项目档案子表的生产团队
      await getAction(this.url.queryProjectTaskList, { projectId: project.id }).then((res) => {
        if (res.success) {
          let { records } = res.result
          let teamTextTemp = []
          let teamIdTemp = []
          records.forEach(item => {
            teamIdTemp.push(item.productTeam);
            teamTextTemp.push(filterMultiDictText(this.dictOptions['teamId'], item.productTeam + ''))
          })
          let productTeamId = teamIdTemp.join(',')
          let productTeamText = teamTextTemp.join(',')
          // 塞入翻译过的团队名称并用逗号拼接
          this.$set(this.model, 'productTeam', productTeamId)
          this.$set(this.model, 'productTeamName', productTeamText);
        }
      })
      // year 业绩归属年度
      this.$set(this.model, 'year', project.year)
      // signUnit 签订单位
      this.$set(this.model, 'signUnit', project.signUnit)
      // ownerUnit 业主单位
      this.$set(this.model, 'ownerUnit', project.ownerUnit)
    },
    htbhChange() {

    },
    // 项目名称
    getProjectDetail(id) {
      const that = this
      this.$nextTick(() => {
        getAction(this.url.queryProjectReportById, { id }).then((res) => {
          if (res.success) {
            const model = res.result
            that.$refs.reportForm.getDetail(model);
            that.$refs.reportForm.title = '项目一览表';
          }
        })
      })
    },
    getContractDetail(id) {
      if (id) {
        this.$refs.contractForm.initData(id);
        this.$refs.contractForm.visible = true;
      }
    },
    getCreateTime() {
      let createTime = this.model.createTime;
      let date = createTime.substring(0, 10)
      return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日';
    },
    // 清空自动带出的字段
    resetAutoFields() {
      this.$set(this.model, 'contractId', '')
      this.$set(this.model, 'contractName', '')
      // 项目编号 finalNo
      this.$set(this.model, 'finalNo', '')
      // 项目承接人 undertaker
      this.$set(this.model, 'undertaker', '')
      // teamName 经营团队
      this.$set(this.model, 'teamName', '')
      // year 业绩归属年度
      this.$set(this.model, 'year', '')
      // signUnit 签订单位
      this.$set(this.model, 'signUnit', '')
      // ownerUnit 业主单位
      this.$set(this.model, 'ownerUnit', '')
      this.$set(this.model, 'productTeam', '')
      this.$set(this.model, 'productTeamName', '');
      // 项目名称
      this.$set(this.model, 'projectName', '')
      this.$set(this.model, 'projectId_dictText', '')
      this.$refs.detailList.dataSource = []
    },
    checkDetail() {
      let checked = true
      this.model.auditLitigationDetail.forEach(detail => {
        if (!detail.paymentMoney) {
          checked = false
        }
      })
      if (!checked) {
        this.$message.warning('请完善诉讼信息!')
        this.confirmLoading = false;
        this.$emit('unButtonDisable');
      }
      return checked;
    },
    // 点击打印
    onPrint () {
        let print = new Print({
          el: '#auditLitigation',
          popTitle: '诉讼单详情 · 禾美环保',
          endCallback() {

          }
        })
      }
  }
}
</script>
